package top.yongyan0624.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import top.yongyan0624.Utils.RedisUtil;
import top.yongyan0624.entity.Message;
import top.yongyan0624.entity.Star;
import top.yongyan0624.mapper.StarMapper;
import top.yongyan0624.service.MessageService;
import top.yongyan0624.service.StarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yongyan
 * @since 2021-05-19
 */
@Service
public class StarServiceImpl extends ServiceImpl<StarMapper, Star> implements StarService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private MessageService messageService;

    @Override
    public void setStar(Star star) {
        int sum = 0;
        if (redisUtil.hasKey("star:" + star.getMsgId())){
            //如果有关注总数缓存，获取关注总数
            sum = (int) redisUtil.get("star:" + star.getMsgId());
        } else {
            //若没有，初始化关注总数
            redisUtil.set("star:" + star.getMsgId(), sum);
        }

        if (star.getStatus()) {
            redisUtil.set("star:" + star.getMsgId(), sum + 1);
        } else {
            redisUtil.set("star:" + star.getMsgId(), sum - 1);
        }

        redisUtil.set("starMsg:" + star.getMsgId() + ":" + star.getUserId() + ":" + star.getPostId(), star.getStatus());
    }

    @Override
    public void handleCache(Star star) {
        if (redisUtil.hasKey("starMsg:" + star.getMsgId() + ":" + star.getUserId() + ":" + star.getPostId())) {
            //若有点赞信息缓存，直接使用
            star.setStatus((Boolean) redisUtil.get("starMsg:" + star.getMsgId() + ":" + star.getUserId() + ":" + star.getPostId()));
        } else {
            //若没有缓存,做缓存
            redisUtil.set("starMsg:" + star.getMsgId() + ":" + star.getUserId() + ":" + star.getPostId(), star.getStatus());
        }
    }

    @Override
    public void transStarFromRedis() {
        Set<String> keys = redisTemplate.keys("star:*");
        for (String key : keys) {
            //获取留言id
            String[] split = key.split(":");
            long msgId = Long.parseLong(split[1]);
            //通过留言id查找到留言记录
            Message msg = messageService.getById(msgId);
            if (msg != null){
                //读取缓存
                msg.setStar((Integer) redisUtil.get(key));
                //更新留言的点赞数，使之持久化
                messageService.updateById(msg);
            }
        }
    }

    @Override
    public void transStarInfoFromRedis() {
        Set<String> keys = redisTemplate.keys("starMsg:*");
        for (String key : keys) {
            //获取点赞信息
            String[] split = key.split(":");
            //封装点赞信息
            long msgId = Long.parseLong(split[1]);
            long userId = Long.parseLong(split[2]);
            long postId = Long.parseLong(split[3]);

            Map<String, Object> map = new HashMap<>();
            map.put("msg_id", msgId);
            map.put("post_id", postId);
            Star star = this.getOne(new QueryWrapper<Star>().allEq(map));

            //持久化
            if (star == null) {
                star = new Star();
                star.setMsgId(msgId);
                star.setUserId(userId);
                star.setPostId(postId);
                star.setStatus((Boolean) redisUtil.get(key));

                this.save(star);
            } else {
                star.setStatus((Boolean) redisUtil.get(key));
                this.update(star, new UpdateWrapper<Star>().allEq(map));
            }
        }
    }
}
